import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:qunaimedical/components/comment_bar.dart';
import 'package:qunaimedical/components/item_comment.dart';
import 'package:qunaimedical/components/loading_indicator.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/comment.dart';
import 'package:qunaimedical/models/health_news.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/comment_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

/// 资讯详情
class NewsDetailPage extends StatefulWidget {
  final HealthNews item;

  const NewsDetailPage({Key key, @required this.item}) : super(key: key);

  @override
  _NewsDetailPageState createState() => _NewsDetailPageState();
}

class _NewsDetailPageState extends State<NewsDetailPage> {
  TextEditingController _commentController = TextEditingController();

  HealthNews _item;
  bool _loading = true;

  /// 评论列表
  List<Comment> _comments = [];

  @override
  void initState() {
    super.initState();
    _fetchData();
    _getCommentList();
  }

  @override
  void dispose() {
    super.dispose();
    _commentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(elevation: 0),
      body: _loading
          ? LoadingIndicator()
          : Column(
              children: [
                Expanded(
                  child: CustomScrollView(
                    slivers: [
                      _buildContent(),
                      SliverToBoxAdapter(
                        child: PrimaryLabel('评论'),
                      ),
                      // 评论列表
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (c, i) => ItemComment(
                            _comments[i],
                            onDelete: () {
                              DialogUtils.showAlertDialog(
                                  context, '提示', '确认删除这条评论？', onPressed: () {
                                Navigator.pop(context);
                                _delete(i);
                              });
                            },
                            onReply: () {
                              Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (c) =>
                                              CommentPage(item: _comments[i])))
                                  .then((value) {
                                if (value != null && value) {
                                  _getCommentList();
                                }
                              });
                            },
                          ),
                          childCount: _comments.length,
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(),
                Row(
                  children: [
                    SafeArea(
                      child: InkWell(
                        onTap: _favorite,
                        child: Container(
                          margin: EdgeInsets.only(left: 8),
                          width: 60,
                          color: Colors.white,
                          alignment: Alignment.center,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(
                                (_item == null ||
                                        _item.whetherAppointed == '0' ||
                                        _item.whetherAppointed == '')
                                    ? 'assets/images/ic_favorite.png'
                                    : 'assets/images/ic_favorited.png',
                                width: 24,
                                height: 24,
                              ),
                              Text(
                                '收藏',
                                style: TextStyle(fontSize: 11),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: CommentBar(
                        hintText: '评论一下',
                        controller: _commentController,
                        onSendPressed: _comment,
                      ),
                    ),
                  ],
                ),
              ],
            ),
    );
  }

  Widget _buildContent() {
    return SliverToBoxAdapter(
      child: Padding(
        padding: EdgeInsets.only(left: 16.0, right: 16.0, bottom: 8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              _item?.infoTitle ?? '',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '${_item?.viewCount ?? 0}人阅读',
                    style: Theme.of(context).textTheme.caption,
                  ),
                  Text(
                    _item?.createDate ?? '',
                    style: Theme.of(context).textTheme.caption,
                  ),
                ],
              ),
            ),
            Html(data: _item?.infoContent),
          ],
        ),
      ),
    );
  }

  void _getCommentList() async {
    var data = await XHttp.postJson(Urls.COMMENT_LIST, {
      "pageNo": 1, // 起始页（必填）
      "pageSize": 1000, // 分页大小（必填）
      "timelyConsultationId": widget.item.id, // 预约单ID/咨询单ID（必填）
      "doctorId": "" // 暂传空字符串（必填）
    });
    if (data != null && mounted) {
      ListResponse response = ListResponse.fromJson(data);
      if (response.code == 1) {
        setState(() {
          _comments = List.from(response.data.map((e) => Comment.fromJson(e)));
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 创建评论
  void _comment() async {
    CommonUtils.hideKeyboard(context);
    String content = _commentController.text.trim();
    if (SPUtils.getUser() == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    if (content.isEmpty) {
      ToastUtil.show('评论内容不能为空', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.COMMENT_ADD, {
      "timelyConsultationId": widget.item.id, // 所评论预约单ID
      "content": content, // 评论内容
      "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
    });
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        _commentController.clear();
        _getCommentList();
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 删除评论
  void _delete(int index) async {
    DialogUtils.showWaitDialog(context);
    // 判断是评论还是回复
    var data;
    if (_comments[index].byRepliedId == null) {
      // 删除评论
      data = await XHttp.postJson(Urls.COMMENT_REMOVE, {
        "id": _comments[index].id, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    } else {
      // 删除回复
      data = await XHttp.postJson(Urls.REPLY_REMOVE, {
        "id": _comments[index].id, // 回复ID
        "commentId": _comments[index].commentId, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    }
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        setState(() {
          _comments.removeAt(index);
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _fetchData() async {
    var data = await XHttp.postJson(Urls.HEALTH_NEWS_DETAIL, {
      "id": widget.item.id,
      "accountId": SPUtils.getUser()?.id ?? '',
    });
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        if (mounted) {
          setState(() {
            _item = HealthNews.fromJson(response.data);
            _loading = false;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 收藏
  void _favorite() {
    CommonUtils.hideKeyboard(context);
    if (SPUtils.getUser() == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    if (_item.whetherAppointed == '0' || _item.whetherAppointed == '') {
      _addFavorite();
    } else {
      _removeFavorite();
    }
  }

  void _addFavorite() async {
    User user = SPUtils.getUser();
    if (user != null && _item != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_ADD, {
        'accountId': user.id,
        'recordId': _item.id,
        'recordType': 'health_info',
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _item.whetherAppointed = '1';
            });
          }
        } else {
          ToastUtil.show(response['msg'], context);
        }
      }
    }
  }

  void _removeFavorite() async {
    User user = SPUtils.getUser();
    if (user != null && _item != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_REMOVE, {
        'accountId': user.id,
        'recordId': _item.id,
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _item.whetherAppointed = '0';
            });
          }
        } else {
          ToastUtil.show(response['msg'], context);
        }
      }
    } else {}
  }
}
